package websocketgulu.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import websocketgulu.demo.websocket.showDiagramWebSocket;

import javax.sound.sampled.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Arrays;

@RestController
@RequestMapping(value = "/api/pcm")
public class GuluTestPCMController {


    @GetMapping(value = "/get")
    public void TestTranscendPCM() {
        try {
            FileInputStream fis = new FileInputStream("C:\\Users\\yoghurts\\IdeaProjects\\咕噜\\北京北京8k16bits单声道.pcm");
            AudioFormat.Encoding encoding =  new AudioFormat.Encoding("PCM_SIGNED");
            AudioFormat format = new AudioFormat(encoding,8000, 16, 1, 2, 16000 ,false);//编码格式，采样率，每个样本的位数，声道，帧长（字节），帧数，是否按big-endian字节顺序存储
            SourceDataLine auline = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            try {
                auline = (SourceDataLine) AudioSystem.getLine(info);
                auline.open(format);
            } catch (LineUnavailableException e) {
                e.printStackTrace();
                return;
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            auline.start();
            byte[] b = new byte[4096];
            int count = 0;
            try {
                while(fis.read(b) != -1) {
                    //auline.write(b, 0, b.length);
                    ByteBuffer byteBuffer = ByteBuffer.wrap(b);
                    Thread.currentThread().sleep(200);  // 300ms的延时会卡
                    // 这里能不能直接发送pcm，然后前端接收
                    if (showDiagramWebSocket.serviceOn())
                        showDiagramWebSocket.sendBinary(byteBuffer);
                    //System.out.println(Arrays.toString(b));
                    count++;
                }
                //auline.close();
                fis.close();
                System.out.println("count:"+count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
